// 公用js方法

import {
	circleUsertep
} from '@/api/my/card.js';

// 计算时间差
const getDateBeforeNow = (stringTime) => {
	if (stringTime) {
		stringTime = new Date(stringTime.replace(/-/g, '/'))

		// 统一单位换算
		var minute = 1000 * 60;
		var hour = minute * 60;
		var day = hour * 24;
		var week = day * 7;
		var month = day * 30;
		var year = month * 12;

		var time1 = new Date().getTime(); //当前的时间戳

		// 对时间进行毫秒单位转换
		var time2 = new Date(stringTime).getTime(); //指定时间的时间戳

		var time = time1 - time2;

		var result = null;
		if (time < 0) {
			// alert("设置的时间不能早于当前时间！");
			result = stringTime;
		} else if (time / year >= 1) {
			result = parseInt(time / year) + "年前";
		} else if (time / month >= 1) {
			result = parseInt(time / month) + "月前";
		} else if (time / week >= 1) {
			result = parseInt(time / week) + "周前";
		} else if (time / day >= 1) {
			result = parseInt(time / day) + "天前";
		} else if (time / hour >= 1) {
			result = parseInt(time / hour) + "小时前";
		} else if (time / minute >= 1) {
			result = parseInt(time / minute) + "分钟前";
		} else {
			result = "刚刚";
		}
		return result;
	} else {
		return
	}
}

// 时间戳转字符串
function happenTimeFun(timestamp, ymd) {
	if (timestamp) {
		var dataTest = typeof timestamp == 'number' ? timestamp.toString() : timestamp
		var date = dataTest.length == 10 ? new Date(timestamp * 1000) : new Date(
			timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
		var Y = date.getFullYear(),
			M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1),
			D = date.getDate(),
			h = ' ' + date.getHours() + ':',
			m = date.getMinutes() + ':',
			s = date.getSeconds();
		//只显示年月日
		if (ymd) {
			if (ymd == 'ymd') {
				return Y + '年' + M + '月' + D + '日'
			} else {
				return Y + '-' + M + '-' + D
			}
			return
		}
		return Y + '-' + M + '-' + D + h + m + s;
	}
	return
}

// 获取当前日期
/**
 * @param {String} str (y-m-d h:i:s) y:年 m:月 d:日 h:时 i:分 s:秒
 */
function dateTimeStr(str) {
	var date = new Date(),
		year = date.getFullYear(), //年
		month = date.getMonth() + 1, //月
		day = date.getDate(), //日
		hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(), //时
		minute = date.getMinutes() < 10 ? date.getMinutes() : date.getMinutes(), //分
		second = date.getSeconds() < 10 ? date.getSeconds() : date.getSeconds(); //秒
	month >= 1 && month <= 9 ? (month = "0" + month) : "";
	day >= 0 && day <= 9 ? (day = "0" + day) : "";
	hour >= 0 && hour <= 9 ? hour : "";
	minute >= 0 && minute <= 9 ? (minute = "0" + minute) : "";
	second >= 0 && second <= 9 ? (second = "0" + second) : "";
	if (str.indexOf('y') != -1) {
		str = str.replace('y', year)
	}
	if (str.indexOf('m') != -1) {
		str = str.replace('m', month)
	}
	if (str.indexOf('d') != -1) {
		str = str.replace('d', day)
	}
	if (str.indexOf('h') != -1) {
		str = str.replace('h', hour)
	}
	if (str.indexOf('i') != -1) {
		str = str.replace('i', minute)
	}
	if (str.indexOf('s') != -1) {
		str = str.replace('s', second)
	}
	return str;
}

// 图片转base64
const urlTobase64 = (url) => {
	return new Promise((resolve, reject) => {
		// #ifdef MP-WEIXIN
		uni.getFileSystemManager().readFile({
			filePath: url, //选择图片返回的相对路径
			encoding: 'base64', //编码格式
			success: res => {
				//成功的回调
				// console.log(res);
				var base64 = 'data:image/jpeg;base64,' + res.data; //不加上这串字符，在页面无法显示的哦
				// return base64
				resolve(base64);
			},
			fail: e => {
				console.log('图片转换失败');
				reject(e);
			}
		});

		// #endif
		// #ifndef MP-WEIXIN
		uni.request({
			url: url,
			method: 'GET',
			responseType: 'arraybuffer',
			success: ress => {
				let base64 = wx.arrayBufferToBase64(ress.data); //把arraybuffer转成base64
				base64 = 'data:image/jpeg;base64,' + base64; //不加上这串字符，在页面无法显示的哦
			},
			fail: e => {
				console.log('图片转换失败');
			}
		});
		// #endif
	});
}

//裁剪分享的图片为5:4
const makeCanvas = (imgUrl) => {
	return new Promise((resolve, reject) => {
		// 获取图片信息,小程序下获取网络图片信息需先配置download域名白名单才能生效
		uni.getImageInfo({
			src: imgUrl,
			success: (imgInfo) => {
				let ctx = uni.createCanvasContext('canvas')
				let canvasW = 0
				let canvasH = imgInfo.height
				// 把比例设置为 宽比高 5:4
				canvasW = (imgInfo.height * 5) / 4
				// 为画框设置背景色，注意要放在画图前，图会覆盖在背景色上
				ctx.fillStyle = "#fff";
				if (imgInfo.width > 225 || imgInfo.height > 180) {
					canvasW = 225;
					canvasH = 180;
					ctx.fillRect(0, 0, canvasW, canvasH);
					let dWidth = canvasW / imgInfo.width; // canvas与图片的宽度比例
					let dHeight = canvasH / imgInfo.height; // canvas与图片的高度比例
					let dWH = imgInfo.width / imgInfo.height; //宽高比
					if (imgInfo.width > canvasW && imgInfo.height > canvasH) {
						if (dWH > 1 && dWH < 1.5) {
							ctx.drawImage(imgInfo.path, (canvasW - imgInfo.width * dHeight) / 2,
								0, imgInfo.width * dHeight, imgInfo
								.height *
								dHeight)
						} else {
							if (imgInfo.width > imgInfo.height) {
								ctx.drawImage(imgInfo.path, 0, (canvasH - imgInfo.height *
										dWidth) / 2, imgInfo.width * dWidth,
									imgInfo.height *
									dWidth)
							}
							if (imgInfo.width == imgInfo.height) {
								ctx.drawImage(imgInfo.path, (canvasW - imgInfo.width *
										dHeight) / 2, 0, imgInfo.width * dHeight,
									imgInfo
									.height * dHeight)
							}
							if (imgInfo.width < imgInfo.height) {
								ctx.drawImage(imgInfo.path, (canvasW - imgInfo.width *
										dHeight) / 2, 0, imgInfo.width * dHeight,
									imgInfo
									.height * dHeight)
							}
						}
					} else {
						if (imgInfo.width > imgInfo.height) {
							ctx.drawImage(imgInfo.path, 0, (canvasH - imgInfo.height) / 2,
								imgInfo.width * dWidth, imgInfo.height)
						}
						if (imgInfo.width == imgInfo.height) {
							ctx.drawImage(imgInfo.path, (canvasW - imgInfo.width * dHeight) / 2,
								0, imgInfo.width * dHeight, imgInfo
								.height *
								dHeight)
						}
						if (imgInfo.width < imgInfo.height) {
							ctx.drawImage(imgInfo.path, (canvasW - imgInfo.width * dHeight) / 2,
								0, imgInfo.width * dHeight, imgInfo
								.height *
								dHeight)
						}
					}
				} else {
					ctx.fillRect(0, 0, canvasW, canvasH)
					ctx.drawImage(
						imgInfo.path,
						0,
						0,
						canvasW,
						canvasH,
						(canvasW - imgInfo.width) / 2, // 宽度从中间向两边填充
						0,
						canvasW,
						canvasH
					)
				}

				ctx.draw(false, () => {
					uni.canvasToTempFilePath({
						width: canvasW,
						height: canvasH,
						destWidth: 750, // 标准的iphone6尺寸的两倍，生成高清图
						destHeight: 600,
						canvasId: "canvas",
						fileType: "jpg", // 注意jpg默认背景为透明
						success: (res) => {
							resolve(res.tempFilePath)
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

// 跳转视频号
const channelsLice = (start, end) => {
	let start_time = Date.parse(new Date(start)),
		end_time = Date.parse(new Date(end));
	console.log(parseInt(start_time), parseInt(end_time));
	return new Promise((resolve, reject) => {
		let liveId = 'sphwDykaf2Q9Bnu'
		// 获取视频号直播信息
		wx.getChannelsLiveInfo({
			finderUserName: liveId,
			startTime: parseInt(
				start_time), //起始时间，筛选指定时间段的直播。若上传了endTime，未上传startTime，则startTime默认为0
			endTime: parseInt(end_time), //结束时间，筛选指定时间段的直播。若上传了startTime，未上传endTime，则endTime默认取当前时间
			success: InfoRes => {
				// 打开视频号直播
				wx.openChannelsLive({
					finderUserName: liveId,
					feedId: InfoRes.feedId,
					nonceId: InfoRes.nonceId,
					success: openRes => {
						// console.log(openRes);
						resolve()
					},
					fail: err => {
						console.log("打开视频号直播失败", err);
						// uni.$u.toast(err.errMsg)
						// reject(err)
					}
				})
			},
			fail: err => {
				console.log("获取视频号直播信息失败", err);
				// reject(err)
				if (err.err_code == 1416104) {
					// 获取直播预告信息
					wx.getChannelsLiveNoticeInfo({
						finderUserName: liveId,
						success: NoticeRes => {
							// console.log("视频号直播预告信息", NoticeRes);
							// 直播预约
							wx.reserveChannelsLive({
								noticeId: NoticeRes.noticeId,
								success: reserveRes => {
									// console.log("预约视频号直播", reserveRes);
									resolve()
								},
								fail: err => {
									console.log("预约视频号直播失败", err);
									uni.$u.toast("直播还未开始")
								}
							})
						},
						fail: err => {
							console.log("获取视频号直播预告信息失败", err);
							uni.$u.toast("直播还未开始")
						}

					})
				} else if (err.err_code == 1416105) {
					uni.$u.toast("当前视频号仅部分人可见")
				} else {
					// uni.$u.toast("获取视频号直播信息失败")
					uni.showModal({
						title: '提示',
						content: '当前视频号直播还未开始,是否进入视频号主页',
						success: res => {
							if (res.confirm) {
								// 打开视频号主页
								wx.openChannelsUserProfile({
									finderUserName: liveId,
									success: ProfileRes => {
										console.log("打开视频号主页成功");
									},
									fail: err => {
										uni.$u.toast("打开视频号主页失败")
									}
								})
							} else {
								return
							}
						}
					})
				}
			}
		})
	})
}
// 富文本图片宽度溢出处理
const formatRichText = (html) => {
	//控制小程序中图片大小
	let newContent = '';
	if (typeof html == 'string') {
		//检测值为字符串才能进行replace操作
		newContent = html.replace(/<img[^>]*>/gi, function(match) {
			match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
			match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
			match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
			return match;
		});
		newContent = newContent.replace(/style="[^"]+"/gi, function(match) {
			match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi,
				'max-width:100%;');
			return match;
		});
		newContent = newContent.replace(/<br[^>]*\/>/gi, '');
		newContent = newContent.replace(/\<img/gi,
			'<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');
		return newContent;
	}
}

// 获取微信步数
const getStep = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			onlyAuthorize: true,
			success: wxRes => {
				uni.getSetting({
					success: result => {
						if (result.authSetting['scope.werun']) {
							// 已授权微信步数--直接更新步数
							getWeRun(wxRes.code);
							resolve()
						} else {
							// 未授权微信步数--去授权
							// uni.setStorageSync('werunAuth', true);
							isAuth(wxRes.code)
							resolve()
						}
					}
				})
			}
		});
	})
}
// 微信步数授权
const isAuth = (code) => {
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope: 'scope.werun',
			success: () => {
				console.log("微信步数授权");
				getWeRun(code);
				resolve()
			},
			fail: (err) => {
				console.log("拒绝微信步数授权");
				// if (uni.getStorageSync('werunAuth') === 'notAuth') {
				// 	// 如果不设置微信步数授权，则不再弹窗提示
				// 	resolve()
				// } else {
				uni.showModal({
					title: '提示',
					content: '未开启步数授权您将无法参与步数大比拼,是否开启',
					success: modelRes => {
						if (modelRes.confirm) {
							//跳转去设置
							wx.openSetting({
								success: setRes => {
									console.log(setRes);
									if (setRes.authSetting[
											'scope.werun']) {
										console.log("设置成功");
										getWeRun(code);
									}
									resolve()
								},
								fail: (err) => {
									resolve()
								}
							});
						} else {
							// 不设置
							// return
							uni.setStorageSync('werunAuth', 'notAuth');
							resolve()
						}
					}
				});
				// }
			}
		});
	})
}
const getWeRun = (code) => {
	return new Promise((resolve, reject) => {
		// 调用小程序方法wx.getWeRunData，获取加密的参数iv，encryptedData等配合增加上一步获取的session_key传给后台
		wx.getWeRunData({
			success: werunRes => {
				// 拿 encryptedData 到开发者后台解密开放数据
				const encryptedData = werunRes.encryptedData;
				const iv = werunRes.iv;
				let msg = {
					// zhanhui_id: this.exhibitionId,
					uid: uni.getStorageSync('userInfo').userId,
					code: code,
					encrypted_data: encryptedData,
					iv: iv
				};
				circleUsertep(msg).then(res => {
					// console.log("运动步数", res);
					resolve();
				});
			},
			fail: res => {
				console.log("微信步数获取失败", res);
				resolve()
				// wx.showModal({
				// 	title: '提示',
				// 	content: '未开通微信运动，请关注“微信运动”公众号后重试',
				// 	showCancel: false,
				// 	confirmText: '知道了'
				// });
			}
		})
	})
}


module.exports = {
	getDateBeforeNow,
	happenTimeFun,
	dateTimeStr,
	urlTobase64,
	makeCanvas,
	channelsLice,
	formatRichText,
	getStep
}